package cs551.listtracker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceActivity;
import android.text.format.Time;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import cs551.listtracker.structure.ListContainer;

public class SettingsActivity extends PreferenceActivity {
	private int dbInt;
	private int histInt;
	private int impInt;

	Intent resultIntent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getActionBar().setTitle("CS551 - Settings");

		dbInt = 0;
		histInt = 0;
		impInt = 0;

		Intent i = getIntent();
		resultIntent = new Intent();

		final ListContainer listContainer = (ListContainer) i
				.getParcelableExtra("lists");

        getPreferenceManager().setSharedPreferencesName(("preferences"));
		
		addPreferencesFromResource(R.xml.settings);

		Button purgeHist = new Button(this);
		purgeHist.setText("Purge History");
		Button purgedb = new Button(this);
		purgedb.setText("Purge Database/Datastore");
		Button initData = new Button(this);
		initData.setText("Fill with Test Data");
		Button expData = new Button(this);
		expData.setText("Export Lists");
		Button impData = new Button(this);
		impData.setText("Import Lists");

		
		getListView().addFooterView(impData);
		getListView().addFooterView(expData);
		getListView().addFooterView(purgeHist);
		getListView().addFooterView(purgedb);
//		getListView().addFooterView(initData);

		purgeHist.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "History Purged",
						Toast.LENGTH_SHORT).show();
				histInt = 1;
				deleteFile("History");

			}
		});

		purgedb.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "Data Purged",
						Toast.LENGTH_SHORT).show();
				dbInt = 2;

				deleteFile("Lists");

			}
		});

		initData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "Data filled",
						Toast.LENGTH_SHORT).show();
				dbInt = 4;

				deleteFile("Lists");

			}
		});

		expData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String state = Environment.getExternalStorageState();

				try {
					if (Environment.MEDIA_MOUNTED.equals(state)) {
						File path = Environment.getExternalStorageDirectory();
						FileOutputStream fos;

						Time t = new Time(Time.getCurrentTimezone());
						t.setToNow();

						File file = new File(
								path.getAbsolutePath() + "/lists/", t
										.format("%d.%m.%Y.%H.%M.%S") + ".xml");
						if (!file.getParentFile().exists())
							file.getParentFile().mkdir();

						fos = new FileOutputStream(file);

						// for (ShoppingList explist : listContainer.lists) {

						listContainer.exportListToWriter(fos);

						fos.close();

						Toast.makeText(getApplicationContext(),
								"Exported: " + file.getName(),
								Toast.LENGTH_SHORT).show();

					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		impData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String state = Environment.getExternalStorageState();

				try {
					if (Environment.MEDIA_MOUNTED.equals(state)) {
						Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
						Uri uri = Uri.parse(Environment
								.getExternalStorageDirectory()
								.getAbsolutePath()
								+ "/lists/");
						intent.setDataAndType(uri, "text/xml");
						startActivityForResult(
								Intent.createChooser(intent, "Import List from: "), 55);

					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 55 && resultCode == RESULT_OK) {

			try {

				Uri uri = data.getData();
				;
				// if (uri != null) {
				InputStream is = getContentResolver().openInputStream(uri);

				System.out.println(data.getDataString());

				// String path = getRealPathFromURI(uri);
				// if (path.toLowerCase().startsWith("file://")) {
				// path = (new File(path)).getAbsolutePath();
				// }
				//
				// File f = new File(path);

				Serializer serializer = new Persister();

				ListContainer listContainer = serializer.read(
						ListContainer.class, is);
				impInt = 8;
				resultIntent.putExtra("lists", listContainer);

				Toast.makeText(getApplicationContext(),
						"Imported " + listContainer.lists.size() + " lists!",
						Toast.LENGTH_SHORT).show();

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	@Override
	public void onBackPressed() {
		System.out.println("Set Result: " + (histInt + dbInt + impInt));
		setResult((histInt + dbInt + impInt), resultIntent);

		super.onBackPressed();
	}

}